<template>
  <div>
    <div class="top">
      <el-button size="small" @click="showYibei = !showYibei;fetchWords()">显示{{ showYibei?'已背':'未背' }}</el-button>
      <el-button size="small" @click="showPronunciation = !showPronunciation">{{ showPronunciation==false?'显示':'隐藏' }}音标列</el-button>
      <el-button size="small" @click="showzhong = !showzhong">{{ showzhong==false?'显示':'隐藏' }}中文列</el-button>
      <el-button size="small" @click="openBatchAddModal">批量添加单词</el-button>
      <el-badge size="small" :max="10000" :value="learnedCount+unlearnedCount" class="item" type="info"> <span>总数</span> </el-badge>
      <el-badge size="small" :max="10000" :value="unlearnedCount" class="item"> 未背 </el-badge>
      <el-badge :max="10000" :value="learnedCount" class="item" type="success"> 已背 </el-badge>
    </div>
    <el-form-item label="搜索">
          <el-input v-model="searchQuery" clearable placeholder="搜索单词"  @blur="searchWords"  @keydown.enter="searchWords" />
    </el-form-item>
    <el-table :data="displayedWords" style="width: 100%">
      <el-table-column type="index" label="序号"  align="center"> </el-table-column>
      <el-table-column prop="word" label="单词">
        <template #default="{ row }">
          <div  class="word-font3-word" :style="{ color:row.color? 'red':'' }">{{ row.word }}</div>
        </template>
      </el-table-column>
      <el-table-column v-if="showPronunciation" prop="pronunciation" label="音标">
        <template #default="{ row }">
          <div class="word-font3" :style="{ color:row.color? 'red':'' }">{{ row.pronunciation }}</div>
        </template>
      </el-table-column>
      <el-table-column v-else prop="pronunciation" label="音标">
        <template #default="{ row }">
          <el-tooltip :content="row.pronunciation" placement="top">
            <span :style="{ color:row.color? 'red':'' }">{{ row.showyin ? row.pronunciation : "音" }}</span>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column v-if="showzhong" label="中文"  align="center">
        <template #default="{ row }">
          <div class="word-font3" :style="{ color:row.color? 'red':'' }">{{ row.meaning }}</div>
        </template>
      </el-table-column>
      <el-table-column v-else label="中文"  align="center">
        <template #default="{ row }">
          <el-tooltip v-if="row.show_chinese===0" :content="row.meaning" placement="top">
            <span :style="{ color:row.color? 'red':'' }">{{ row.showMeaning ? row.meaning : "中" }}</span>
          </el-tooltip>
          <span :style="{ color:row.color? 'red':'' }" v-else>{{ row.meaning }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作"  align="center">
        <template #default="{ row }">
          <el-button size="small" v-if="row.learned==0" @click="markAsLearned(row.id)">+</el-button>
          <el-button size="small" v-else @click="markAsUnLearned(row.id)">-</el-button>
          <el-button size="small"  @click="markAsShowChinese(row.id,row.show_chinese)">Ch</el-button>
          <el-button size="small"  @click="markAsColor(row.id,row.color)">Co</el-button>
          <el-button size="small"  @click="openEditMeaningModa(row)">E</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <el-pagination
        background
        layout=" prev, pager, next"
        :total="totalWords"
        :page-sizes="[10, 20, 50, 100]"
        :current-page="currentPage"
        :page-size="pageSize"
        @current-change="handleCurrentChange"
      ></el-pagination>
    </div>

    <!-- 悬浮按钮 -->
    <div class="floating-buttons">
      <el-button circle icon="ArrowUpBold" @click="scrollToTop"></el-button>
      <el-button circle icon="Fold" @click="openOperationPanel"></el-button>
    </div>

    <!-- 操作面板 -->
    <el-drawer v-model="operationPanelVisible" direction="rtl" size="50%" :with-header="false">
      <el-form label-position="top">
        <el-form-item label="跳转到第几页">
          <el-input-number v-model="jumpPage" :min="1" :max="Math.ceil(totalCount / pageSize)" @change="jumpToPage" />
        </el-form-item>
        <el-form-item label="每页显示条目数">
          <el-select v-model="pageSizeValue" @change="updatePageSize">
            <el-option v-for="item in pageSizeOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
       
      </el-form>
    </el-drawer>

    <!-- Batch add modal -->
    <el-dialog v-model="batchAddModalVisible" title="批量添加单词" width="80%">
      <el-input v-model="batchInput" type="textarea" :rows="10" placeholder="粘贴单词列表"></el-input>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="batchAddModalVisible = false">取消</el-button>
          <el-button type="primary" @click="processWords">处理单词</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 修改单词中文备注模态框 -->
    <el-dialog v-model="editMeaningModalVisible" title="修改单词中文备注" width="80%">
      <el-input v-model="batchInput2" type="textarea" :rows="10" placeholder="请输入中文备注"></el-input>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editMeaningModalVisible = false">取消</el-button>
          <el-button type="primary" @click="editMeaningModalOk">提交</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- Preview modal -->
    <el-dialog v-model="previewModalVisible" title="预览单词列表" width="80%">
      <el-table :data="processedWords" style="width: 100%">
        <el-table-column type="index" label="序号" width="50"> </el-table-column>
        <el-table-column prop="word" label="单词" width="120"> </el-table-column>
        <el-table-column prop="pronunciation" label="音标" width="120"> </el-table-column>
        <el-table-column prop="meaning" label="含义" width="200"> </el-table-column>
      </el-table>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="previewModalVisible = false">关闭</el-button>
          <el-button type="primary" @click="submitWords">提交到数据库</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import axios from "axios";
// axios.defaults.baseURL = "http://127.0.0.1:3000/api";
axios.defaults.baseURL = "/api";
import { ElMessage } from 'element-plus';
import { ref, onMounted, watch } from "vue";

const searchQuery = ref("");
const batchInput = ref("");
const batchInput2 = ref("");
let id = null;
const processedWords = ref([]);
const words = ref([]);
const displayedWords = ref([]);
const currentPage = ref(1);
const pageSize = ref(10);
const totalWords = ref(0);
const batchAddModalVisible = ref(false);
const editMeaningModalVisible = ref(false);
const previewModalVisible = ref(false);
const operationPanelVisible = ref(false);
const jumpPage = ref(1);
const pageSizeValue = ref(10);
const pageSizeOptions = [
  { value: 10, label: "10条/页" },
  { value: 20, label: "20条/页" },
  { value: 50, label: "50条/页" },
  { value: 100, label: "100条/页" },
];
const showYibei = ref(true) //已背
const showPronunciation = ref(true);
const showzhong = ref(true);
const learnedCount = ref(0);
const unlearnedCount = ref(0);
const totalCount = ref(0);
// 打开批量添加单词模态框
function openBatchAddModal() {
  batchAddModalVisible.value = true;
}
// 打开修改单词中文备注模态框
function openEditMeaningModa(row) {
  batchInput2.value=row.meaning
  id=row.id
  editMeaningModalVisible.value = true;
}
// 修改中文备注ok
async function editMeaningModalOk() {
  try {
    await axios.patch(`/words/meaning/${id}`, { meaning: batchInput2.value });
    editMeaningModalVisible.value = false
    await fetchWords(currentPage.value, pageSize.value); // Refresh the list
  } catch (error) {
    console.error("Error 修改中文备注:", error);
    if (error.response && error.response.status === 403) {
      ElMessage.error("没有权限操作");
    } else {
      ElMessage.error("无法修改中文备注，请检查网络连接或稍后再试。");
    }
  }
}
// 处理单词列表
function processWords() {
  const lines = batchInput.value.split("\n").map((line) => line.trim());
  const processed = lines
    .map((line) => {
      const match = line.match(/^(.+?)\s*\[([^\]]*)\]\s*(.*)$/);
      if (match) {
        const word = match[1].trim();
        const pronunciation = `[${match[2]}]`;
        const meaning = match[3].trim();
        return {
          word: word,
          pronunciation: pronunciation,
          meaning: meaning,
          showMeaning: false,
          showyin: false,
        };
      }
      return null;
    })
    .filter((word) => word); // 过滤掉空行
  processedWords.value = processed;
  previewModalVisible.value = true;
}
// 提交单词到数据库
async function submitWords() {
  try {
    const response = await axios.post("/words/batch", processedWords.value);
    await fetchWords(currentPage.value, pageSize.value); // Refresh the list
    batchInput.value = ""; // 清空输入框
    processedWords.value = []; // 清空预览列表
    batchAddModalVisible.value = false; // 关闭模态框
  } catch (error) {
    console.error("Error submitting words:", error);
    if (error.response && error.response.status === 403) {
      ElMessage.error("没有权限操作");
    } else {
      ElMessage.error("无法提交单词，请检查网络连接或稍后再试。");
    }
  }
}
// 获取所有未掌握的单词列表
async function fetchWords(page = 1, size = pageSize.value) {
  let response = null
  try {
    if(showYibei.value){
       response = await axios.get("/words/learnedList", { params: { page, size } });
    }else{
      response = await axios.get("/words/unlearnedList", { params: { page, size } });
    }
    
    const data = response.data.words;

    displayedWords.value = data;
    learnedCount.value = response.data.learnedCount;
    unlearnedCount.value = response.data.unlearnedCount;
    totalCount.value =showYibei.value? response.data.unlearnedCount:response.data.learnedCount;
    totalWords.value =showYibei.value? Number(response.data.unlearnedCount):Number(response.data.learnedCount);
    
  } catch (error) {
     console.error("Error fetching words:", error);
    if (error.response && error.response.status === 403) {
      ElMessage.error("没有权限操作");
    } else {
      ElMessage.error("无法加载单词列表，请检查网络连接或稍后再试。");
    }
  }
}

// 标记单词为显示中文或不显示中文
async function markAsShowChinese(id, value) {
  value=value==0?1:0
 
  try {
    await axios.patch(`/words/show_chinese/${id}`, { show_chinese: value });
    await fetchWords(currentPage.value, pageSize.value); // Refresh the list
  } catch (error) {
    console.error("Error marking word as show_chinese:", error);
    if (error.response && error.response.status === 403) {
      ElMessage.error("没有权限操作");
    } else {
      ElMessage.error("无法标记单词为显示中文，请检查网络连接或稍后再试。");
    }
  }
}

// 标记单词为显示颜色
async function markAsColor(id, value) {
  value=value==0?1:0
 
  try {
    await axios.patch(`/words/color/${id}`, { color: value });
    await fetchWords(currentPage.value, pageSize.value); // Refresh the list
  } catch (error) {
    console.error("Error marking word as color:", error);
    if (error.response && error.response.status === 403) {
      ElMessage.error("没有权限操作");
    } else {
      ElMessage.error("无法标记单词为显示中文，请检查网络连接或稍后再试。");
    }
  }
}
// 标记单词为已掌握
async function markAsLearned(id) {
  try {
    await axios.patch(`/words/learned/${id}`);
    await fetchWords(currentPage.value, pageSize.value); // Refresh the list
  } catch (error) {
    console.error("Error marking word as learned:", error);
     if (error.response && error.response.status === 403) {
      ElMessage.error("没有权限操作");
    } else {
      ElMessage.error("无法标记单词为已掌握，请检查网络连接或稍后再试。");
    }
  }
}
// 标记单词为未掌握
async function markAsUnLearned(id) {
  try {
    await axios.patch(`/words/unlearned/${id}`);
    await fetchWords(currentPage.value, pageSize.value); // Refresh the list
  } catch (error) {
    console.error("Error marking word as learned:", error);
     if (error.response && error.response.status === 403) {
      ElMessage.error("没有权限操作");
    } else {
      ElMessage.error("无法标记单词为未掌握，请检查网络连接或稍后再试。");
    }
  }
}
// 搜索单词
async function searchWords() {
  try {
    const response = await axios.get("/words/search", {
      params: { q: searchQuery.value, page: currentPage.value, size: pageSize.value },
    });
    const data = response.data;
    totalWords.value = data.totalCount;
    displayedWords.value = data.words;
  } catch (error) {
    console.error("Error searching words:", error);
     if (error.response && error.response.status === 403) {
      ElMessage.error("没有权限操作");
    } else {
      ElMessage.error("无法搜索单词，请检查网络连接或稍后再试。");
    }
  }
}

// 跳转到指定页
async function jumpToPage(page) {
  currentPage.value = page;
  await fetchWords(page, pageSize.value);
  scrollToTop()
}
// 分页处理
async function handleCurrentChange(val) {
  currentPage.value = val;
  await fetchWords(val, pageSize.value);
  scrollToTop()

}
// 更新每页显示的条目数
async function updatePageSize(size) {
  pageSize.value = size;
  await fetchWords(currentPage.value, size);
  scrollToTop()

}

// 返回页面顶部
function scrollToTop() {
  window.scrollTo({
    top: 0,
    behavior: "smooth",
  });
}

// 打开操作面板
function openOperationPanel() {
  operationPanelVisible.value = true;
}

// 其他函数保持不变

onMounted(() => {
  fetchWords();
});

// watch(searchQuery, () => {
//   if (searchQuery.value) {
//     searchWords();
//   } else {
//     fetchWords(currentPage.value, pageSize.value);
//   }
// });
</script>
<style scoped>
/* Add some basic styling */
:deep(.el-table .cell) {
  box-sizing: border-box;
  line-height: 23px;
  overflow: visible;
  overflow-wrap: normal;
  padding: 0 12px;
  text-overflow: unset;
  white-space: normal;
}

.top {
  display: flex;
  margin: 10px auto;
  justify-content: space-around;
  align-items: center;
}
.pagination {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 40px;
  margin-top: 10px;
  overflow-x: auto; /* 添加水平滚动条 */
  -webkit-overflow-scrolling: touch; /* 使滚动更加流畅（仅限 Safari 和 iOS） */
}

/* 限制分页组件的最大宽度 */
.pagination > .el-pagination {
  max-width: 100%;
}

/* 隐藏滚动条但保持滚动功能 */
.pagination::-webkit-scrollbar {
  height: 0;
  width: 0;
}

/* 在小屏幕设备上隐藏分页组件的滚动条 */
@media (max-width: 768px) {
  .pagination {
    overflow-x: hidden;
  }
  .pagination > .el-pagination {
    white-space: nowrap; /* 保持分页组件内容为一行 */
  }
}

.floating-buttons {
  position: fixed;
  bottom: 20px;
  right: 20px;
  display: flex;
  gap: 10px;
  z-index: 9999;
}
.item {
  font-size: 14px;
  font-weight: 100;
}

.word-font1 {
  font-family: Arial, sans-serif;
  font-size: 12pt;
  line-height: 1.5;
}

.word-font2 {
  font-family: Calibri, sans-serif;
  font-size: 12pt;
  line-height: 1.5;
}

.word-font3 {
  font-family: "Times New Roman", serif;
  font-size: 12pt;
  line-height: 1.5;
}

.word-font3-word{
   font-family: "Times New Roman", serif;
  font-size: 14pt;
  line-height: 1.5;
  color: #000000;
  font-weight: 600;
}

</style>
